﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Text;

namespace System.Web.Mvc
{
    /// <summary>
    /// 上传类别
    /// </summary>
    public struct UploadType
    {
        public const string Img = "*.jpg;*.gif;*.png;*.rar";

        public const string Zip = "*.zip;*.rar;*.7z";

        public const string Office = "*.doc;*.xls;*.ppt";
    }

    /// <summary>
    /// 上传配置
    /// </summary>
    public class UploadConfig
    {
        private string _ButImg = "SWFUpload/Flash/wqswfupload.png";

        public string ButImg
        {
            get { return _ButImg; }
            set { _ButImg = value; }
        }

        private string _UploadSaveUrl = "~/Home/PublicReuse/UploadFile";
        /// <summary>
        /// 文件保存路径
        /// </summary>
        public string UploadSaveUrl
        {
            get { return _UploadSaveUrl; }
            set { _UploadSaveUrl = value; }
        }

        private string _UploadFlashUrl = "SWFUpload/Flash/swfupload.swf";
        /// <summary>
        /// swf文件路径
        /// </summary>
        public string UploadFlashUrl
        {
            get { return _UploadFlashUrl; }
            set { _UploadFlashUrl = value; }
        }

        private string _FileSizelimit = "200 MB";
        /// <summary>
        /// 文件大小限制
        /// </summary>
        public string FileSizelimit
        {
            get { return _FileSizelimit; }
            set { _FileSizelimit = value; }
        }

        string _Callback = " function(e){ } ";
        /// <summary>
        /// 完成回调 callBack(server_data);
        /// </summary>
        public string Callback
        {
            get { return _Callback; }
            set { _Callback = value; }
        }

        string _PostParams="{}";
        /// <summary>
        /// 上传文件附带参数，可以是function和json
        /// 如果是function,将function执行结果值做为参数发送（function返回值必须是josn）
        /// 如果json对象，直接做为参数发送
        /// </summary>
        public string PostParams
        {
            get { return _PostParams; }
            set { _PostParams = value; }
        }
    }

    /// <summary>
    /// 上传控件扩展
    /// </summary>
    public static class UploadExtensions
    {
      
        /// <summary>
        /// 编辑器脚本引用
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="contentPath"></param>
        /// <returns></returns>
        public static HtmlString UploadScript(this UrlHelper helper)
        {
            const string template = " <script src='{0}' type='text/javascript'></script>";

            string url = UrlExtensions.GetUrlString(helper, template, "SWFUpload/swfupload.js");
            string lang = UrlExtensions.GetUrlString(helper, template, "SWFUpload/swfuploadPlus.js");

            return new HtmlString(url + lang);
        }

        /// <summary>
        /// 上传控件
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="config">上传配置</param>
        /// <param name="uploadType">上传类别</param>
        /// <param name="callback">回调方法</param>
        /// <returns></returns>
        public static MvcHtmlString Upload(this HtmlHelper htmlHelper, UploadConfig config, string uploadType, string modelId="")
        {
            return MvcHtmlString.Create(Upload(htmlHelper, config, uploadType, "", modelId).ToString());
        }

        /// <summary>
        /// 上传控件生成
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="config"></param>
        /// <param name="uploadType"></param>
        /// <param name="callback"></param>
        /// <param name="inputName"></param>
        /// <param name="modelId"></param>
        /// <returns></returns>
        private static string Upload(this HtmlHelper htmlHelper, UploadConfig config, string uploadType, string inputName, string modelId)
        {

            UrlHelper Url = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

            //文件保存路径
            string uploadUrl =     Url.Content(config.UploadSaveUrl) + "?modelId=" + modelId;

            //swf文件路径
            string flashUrl = UrlExtensions.GetUrlString(Url, "{0}", config.UploadFlashUrl);

            //随机ID
            string raId = Guid.NewGuid().ToString();

            //图片按钮
            string butImg = UrlExtensions.GetUrlString(Url, "{0}", config.ButImg); ;

            //上传控件ID
            string swfId = string.Format("swfUpload{0}", raId);

            //进度div
            string scheduleing_div = string.Format("scheduleing_div{0}", raId);

            //进度div
            string oK_div = string.Format("OK_div{0}", raId);

            //进度div
            string schedule_div = string.Format("schedule_div{0}", raId);


            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(" <div style='width:220px'><div style='float:left'><input type=\"button\" id=\"" + swfId + "\"  /> </div> ");
            sb.Append(" <div id=\"" + schedule_div + "\" style=\" float:right;width: 100px;margin-top:5px; margin-bottom:5px; height: 20px; background-color: #E6EAF0;\"> ");
            sb.Append("     <div id=\"" + scheduleing_div + "\" style=\"background-color: #95A1B6; width: 100px; height: 20px; z-index: 2\"> ");
            sb.Append("     </div> ");
            sb.Append(" </div> ");

            sb.Append(" <div id=\"" + oK_div + "\"  style=\" float:right;width: 100px;margin-top:10px; margin-bottom:5px; height: 20px;\"> ");
            sb.Append("    上传完成. ");
            sb.Append(" </div>  </div>");

            sb.Append(" <script> ");
            sb.Append("     $(function () ");
            sb.Append("     { ");
            sb.Append("         var uploadDiv = ");
            sb.Append("        { ");
            sb.Append("            callBack: " + config.Callback + ", ");
            sb.Append("            schedule_div: '#" + schedule_div + "', ");
            sb.Append("            scheduleing_div: '#" + scheduleing_div + "', ");
            sb.Append("            oK_div: '#" + oK_div + "', ");
            sb.Append("            SWFUploadId: '" + swfId + "', ");
            sb.Append("            upload_url: '" + uploadUrl + "', ");
            sb.Append("            flash_url: '" + flashUrl + "', ");
            sb.Append("            file_types: '" + uploadType + "', ");
            sb.Append("            inputName: '#" + inputName + "', ");
            sb.Append("            button_image_url: '" + butImg + "', ");
            sb.Append("            file_size_limit: '" + config.FileSizelimit + "', ");
            sb.Append("            param_object: " + config.PostParams + ", ");
            sb.Append("            curr_file: null ");
            sb.Append("        }; ");
            sb.Append("         swfuploadInfo(uploadDiv); ");
            sb.Append("     }); ");
            sb.Append(" </script> ");

            return sb.ToString();

        }

        /// <summary>
        /// 上传控件
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression"></param>
        /// <param name="config"></param>
        /// <param name="uploadType"></param>
        /// <param name="modelId"></param>
        /// <returns></returns>
        public static MvcHtmlString UploadFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, UploadConfig config, string uploadType, string modelId = "")
        {
            var metadata = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, htmlHelper.ViewData);

            //获取对象名称
            string name = metadata.PropertyName;
            string htmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
            var value=htmlHelper.ViewData.Eval(name);

            StringBuilder tagBuilder = new StringBuilder();
            tagBuilder.Append(" <input  type='hidden'   name='" + htmlFieldName + "'  Id='" + htmlFieldName + "'  value='" + value + "'   />");

            return MvcHtmlString.Create(Upload(htmlHelper, config, uploadType, htmlFieldName, modelId).ToString() + tagBuilder.ToString());
        }
    }


  
}